package leetcode.code0457;

import leetcode.IDebug;
import leetcode.helper.HelpDebug;

public class Solution implements IDebug {

	public boolean circularArrayLoop(int[] nums) {
		int len = nums.length;
		int p = 0;
		while (p < len) {
			int cur = nums[p];
			if (cur != 0) {
//				Set<Integer> tos = new HashSet<>();
//				tos.add(p);
				nums[p] = 0;
				int last = p;
				int start = p;
				boolean direction = cur > 0;
				int next = this.next(p, cur, len);
				while ((cur = nums[next]) != 0 && next != last) {
					if ((cur > 0 && direction) || (!direction && cur < 0)) {
						nums[next] = 0;
//						tos.add(next);
						last = next;
						next = this.next(next, cur, len);
					} else {
						break;
					}
				}
				if (next==start && next != last) {
					return true;
				}
//				if (tos.size() > 1 && tos.contains(next) && next != last) {
//					return true;
//				}
			}
			p++;
		}
		return false;
	}

	public int next(int cur, int step, int len) {
		int next = (cur + step) % len;
		if (next >= 0 && next < len) {
			return next;
		} else if (next >= len) {
			return next % len;
		} else {
			return len + next;
		}
	}

	@Override
	public void debug1() {
		HelpDebug.compare(false, this.circularArrayLoop(HelpDebug.str2array3("[-1,2]")));
	}

	@Override
	public void debug2() {
		// TODO Auto-generated method stub

		HelpDebug.compare(true, this.circularArrayLoop(HelpDebug.str2array3("[2,-1,1,2,2]")));
	}

	@Override
	public void debug3() {
		// TODO Auto-generated method stub
		HelpDebug.compare(false, this.circularArrayLoop(HelpDebug.str2array3("[-2,1,-1,-2,-2]")));

	}

	@Override
	public void debug4() {
		// TODO Auto-generated method stub
		HelpDebug.compare(true, this.circularArrayLoop(HelpDebug.str2array3("[1,1,2]")));

	}

	public void debug5() {
		// TODO Auto-generated method stub
		HelpDebug.compare(false, this.circularArrayLoop(HelpDebug.str2array3("[-1,-2,-3,-4,-5]")));

	}

	public void debug6() {
		// TODO Auto-generated method stub
		HelpDebug.compare(false, this.circularArrayLoop(HelpDebug.str2array3("[-2,-3,-9]")));

	}

	public static void main(String[] args) {
		Solution so = new Solution();
		so.debug5();
		so.debug1();
		so.debug2();
		so.debug4();
		so.debug3();
		so.debug6();

	}

}
